from flask import Flask
from flask_cors import CORS
from config import config
from extensions import db, migrate
from utils.error_handler import register_error_handlers
from utils.logger import setup_logger
from flask_restx import Api, Namespace
from controllers.user_controller import api as user_ns
from controllers.store_controller import api as store_ns
from controllers.order_controller import api as order_ns
from controllers.investment_controller import api as investment_ns
from controllers.profit_controller import api as profit_ns
from controllers.hierarchy_controller import api as hierarchy_ns
from controllers.product_controller import api as product_ns
from controllers.card_package_controller import api as card_package_ns
from controllers.card_consumption_controller import api as card_consumption_ns
from extensions import jwt

def create_app(config_name='default'):
    """应用工厂函数"""
    app = Flask(__name__)
    # 添加CORS支持
    CORS(app, resources={r"/*": {"origins": "*"}})
    app.config.from_object(config[config_name])
    # 注册请求预处理中间件
    @app.before_request
    def before_request():
        from utils.auth import preprocess_request
        preprocess_request()
    # 初始化RESTX扩展
    api = Api(
        title='理发店管理系统API',
        version='1.0',
        description='理发店管理系统接口文档',
        doc='/swagger'
    )
    
    # 初始化扩展
    CORS(app)
    db.init_app(app)
    migrate.init_app(app, db)
    
    # 初始化JWT扩展
    jwt.init_app(app)
    
    # 注册命名空间
    api.add_namespace(user_ns, path='/api/users')
    api.add_namespace(store_ns, path='/api/stores')
    api.add_namespace(order_ns, path='/api/orders')
    api.add_namespace(investment_ns, path='/api/investments')
    api.add_namespace(profit_ns, path='/api/profits')
    api.add_namespace(hierarchy_ns, path='/api/hierarchies')
    api.add_namespace(product_ns, path='/api/products')
    api.add_namespace(card_package_ns, path='/api/card_packages')
    api.add_namespace(card_consumption_ns, path='/api/card_consumptions')
    # 注册RESTX接口
    api.init_app(app)
    
    # 注册错误处理
    register_error_handlers(app)
    
    # 设置日志
    setup_logger(app)
    
    return app

if __name__ == '__main__':
    app = create_app()
    app.run(host='0.0.0.0', port=9999, debug=True)